#include "pub_sub/subscriber.h"
#include "pub_sub/pub_sub_infos.h"
#include <fcntl.h>
#include <sys/eventfd.h>
#include <unistd.h>

#include "log/logger.h"

template <typename MsgType>
Subscriber<MsgType>::Subscriber(const std::string &topic_name)
    : topic_name_(topic_name) {
  std::string queue_path = "/tmp/" + topic_name_ + "_Q";
  msgq_ = make_shared_msgq(queue_path);
  msgq_->init_subscriber();
}

template <typename MsgType> Subscriber<MsgType>::~Subscriber() {
  SubInfosManager::getInstance().unregisterSubscriber(topic_name_);
}

template <typename MsgType>
bool Subscriber<MsgType>::Subscribe(const std::string &topic_name, SubCallback callback) {
  int efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
  if (efd == -1) {
      JC_ERROR("create eventfd failed, topic_name: {}, efd: {}", topic_name, efd);
      return false;
  }

  SubscriberInfo sub_info(efd, callback, topic_name);
  return SubInfosManager::getInstance().registerSubscriber(topic_name, sub_info);
}